package com.yq.testmodule.paging3

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.zxw.net.NewsApiService
import com.yq.testmodule.entity.NewsListEntity

class TestPagingSource : PagingSource<Int, NewsListEntity>() {
    override fun getRefreshKey(state: PagingState<Int, NewsListEntity>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NewsListEntity> {
        return try {
            val page = params.key ?: 1
            val rspRepository = NewsApiService.getNewsList("home", page, "chs", "")
            val items = rspRepository.data!!
            val preKey = if (page > 1) page - 1 else null
            val nextKey = if (items.isNotEmpty()) page + 1 else null
            LoadResult.Page(items, preKey, nextKey)

        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}